﻿<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/_layouts/application.master" Inherits="Microsoft.SharePoint.WebControls.UnsecuredLayoutsPageBase, Microsoft.SharePoint"%>
<%@ Import Namespace="System.Resources"%>
<%@ Import Namespace="System.Globalization"%>
<%@ Import Namespace="Microsoft.SharePoint.Administration"%>
<%@ Import Namespace="SharePointOfView.SPReporting"%>
<%@ Import Namespace="SharePointOfView.SPReporting.Jobs"%>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace="Microsoft.SharePoint.Utilities" %>
<%@ Register TagPrefix="wssuc" TagName="InputFormSection" src="~/_controltemplates/InputFormSection.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="InputFormControl" src="~/_controltemplates/InputFormControl.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ButtonSection" src="~/_controltemplates/ButtonSection.ascx" %>
<%@ Register TagPrefix="SoV" Namespace="SharePointOfView.SPReporting" Assembly="SharePointOfView.SPReporting, Version=1.0.0.0, Culture=neutral, PublicKeyToken=85a56337686e234b" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral,PublicKeyToken=71e9bce111e9429c" %>
<asp:Content ID="Content1" ContentPlaceHolderId="PlaceHolderPageTitle" runat="server"><asp:Literal ID="litPageTitle" runat="server" /></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderId="PlaceHolderPageTitleInTitleArea" runat="server"><asp:Literal ID="litPageTitle2" runat="server" /></asp:Content>
<asp:Content id="Breadcrumb" contentplaceholderid="PlaceHolderTitleBreadcrumb" runat="server">
<asp:HyperLink ID="hlSite" runat="server" /> &gt; <asp:HyperLink ID="hlSiteSettings" runat="server" Text="<%$Resources:spadmin,applications_pagetitle%>" /> &gt; <asp:Label CssClass="ms-sitemapdirectional" ID="lbCurrentPage" runat="server" />
</asp:Content>
<asp:Content ID="PageDescription" ContentPlaceHolderID="PlaceHolderPageDescription" runat="server">
SharePoint of View - SPReporting on CodePlex : <a href="http://sovspreporting.codeplex.com/" target="_blank">Home (Wiki)</a>, <a href="http://sovspreporting.codeplex.com/Release/ProjectReleases.aspx#ReleaseFiles" target="_blank">Downloads</a>, <a href="http://sovspreporting.codeplex.com/Thread/List.aspx" target="_blank">Discussions</a>, <a href="http://sovspreporting.codeplex.com/WorkItem/List.aspx" target="_blank">Issue Tracker</a>
</asp:Content>
<asp:Content ID="MainContent" ContentPlaceHolderId="PlaceHolderMain" runat="server">
 <table class="propertysheet" border="0" width="100%" cellspacing="0" cellpadding="0" id="diidSettings">
	<wssuc:InputFormSection id="ifsReportsCenterUrl" runat="server">
		<Template_Description>
            <H3 class="ms-standardheader"><SharePoint:EncodedLiteral id="elitReportsCenterUrlTitle" runat="server" EncodeMethod='HtmlEncode'/></H3>
			<SharePoint:EncodedLiteral id="elitReportsCenterUrlDescription" runat="server" EncodeMethod='HtmlEncode'/>
	   </Template_Description>
	   <Template_InputFormControls>
            <wssuc:InputFormControl id="ifcReportsCenterUrl" runat="server">
				 <Template_Control>
				 <TABLE border="0" cellpadding="0" cellspacing="0" dir="ltr">
				    <TR nowrap="">
					    <TD class="ms-authoringcontrols">
    					    <asp:TextBox ID="txtbxReportsCenterUrl" runat="server" />
		    				<asp:HyperLink ID="hlReportsCenter" runat="server" Text="Go to the Reports Center" Target="_blank" /><br />
		    				<asp:Label ID="lbReportActivationInfo" runat="server" EnableViewState="false" />
		    				<br /> 
		    				<asp:Button ID="btActivateReportsCenter" runat="server" Text="Activate" />
                            <asp:Button ID="btDeactivateReportsCenter" runat="server" Text="Deactivate" />
					    </TD>
				    </TR>
				    <TR nowrap="">
					    <TD class="ms-authoringcontrols">
    					    <SharePoint:EncodedLiteral runat="server" id="elitDefaultReportsCenterUrl" EncodeMethod='HtmlEncode'/>
					        <SharePoint:EncodedLiteral runat="server" id="elitDefaultReportsCenterUrlChoice" />
					    </TD>
					</TR>
				 </TABLE>
				 </Template_Control>
			</wssuc:InputFormControl>
	   </Template_InputFormControls>
	</wssuc:InputFormSection>
</table>
<asp:Panel ID="pnReportsCenterActivated" runat="server" Visible="false">
<h3><asp:Label ID="lbFeaturesSection" runat="server" /></h3>
		<TABLE border="0" width="100%" cellspacing="0" cellpadding="0">
			<TR>
				<TD colspan="2">
<asp:Repeater ID="rptrFeatureList" runat="server">
	<HeaderTemplate>
		<TABLE width="100%" cellpadding="0" cellspacing="0" border="0">
			<colgroup>
				<col width="5%">
				<col width="85%">
				<col width="5%">
				<col width="5%">
			</colgroup>
			<TR>
				<TH scope="col" ID="FeatureIcon" class="ms-vh2" style="padding-bottom: 4px"></TH>
				<TH scope="col" ID="FeatureTitleDescription" class="ms-vh2" style="padding-bottom: 4px"><SharePoint:EncodedLiteral runat="server" text="<%$Resources:wss,ManageFeatures_NameHeading%>" EncodeMethod='HtmlEncode'/></TH>
				<TH scope="col" ID="FeatureActiveButton" class="ms-vh2" style="padding-bottom: 4px">&nbsp;</TH>
				<TH scope="col" ID="FeatureActiveState" class="ms-vh2" style="padding-bottom: 4px"><SharePoint:EncodedLiteral runat="server" text="<%$Resources:wss,ManageFeatures_StatusHeading%>" EncodeMethod='HtmlEncode'/></TH>
			</TR>
			<TR>
	</HeaderTemplate>
	<ItemTemplate>
		<TD class="ms-alternating" style="padding-top: 4px; padding-bottom: 4px; padding-left: 8px; padding-right: 8px;">
			<IMG src='/_layouts/images/<%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container.DataItem, "ImageUrl", "")) %>'
				alt='<%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container.DataItem,"ImageAlt", "")) %>'></IMG>
		</TD>
		<TD class="ms-alternating" style="padding-top: 4px; padding-bottom: 4px; ">
			<TABLE width="100%" cellpadding="0" cellspacing="0" border="0">
				<TR><TD class="ms-vb2" style="font-weight: bold;"><H3 class="ms-standardheader"><%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container.DataItem, "Title", "")) %></H3></TD></TR>
				<TR><TD class="ms-vb2"><%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container.DataItem, "Description", "")) %></TD></TR>
			</TABLE>
		</TD>
		<TD class="ms-alternating" style="padding-top: 4px; padding-bottom: 4px;">
			<DIV id='<%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container.DataItem, "FeatureId", "")) %>'>
				<asp:Button runat="server" UseSubmitBehavior="false" class="ms-ButtonHeightWidth"
							id='btnActivate'
							OnClick="BtnActivateFeature_Click"
							CommandName='<%# DataBinder.Eval(Container.DataItem, "Status") %>'
							CommandArgument='<%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container.DataItem, "FeatureId", "")) %>'
							Text='<%# DataBinder.Eval(Container.DataItem, "ButtonText") %>' />&nbsp;&nbsp;&nbsp;&nbsp;
			</DIV>
		</TD>
		<TD class="ms-alternating" style="padding-top: 4px; padding-bottom: 4px; ">
			<div class="ms-vb2 ms-featurestatus" FeatureStatus='<%# DataBinder.Eval(Container.DataItem, "Status") %>'>
				<span class="ms-featurestatustext"><%# DataBinder.Eval(Container.DataItem, "StatusUI") %></span>&nbsp;
			</div>
		</TD>
	</ItemTemplate>
	<AlternatingItemTemplate>
		<TD class="ms-alternating ms-featurealtrow" style="padding-top: 4px; padding-bottom: 4px;  padding-left: 8px; padding-right: 8px;">
			<IMG src='/_layouts/images/<%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container.DataItem, "ImageUrl", "")) %>'
				alt='<%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container.DataItem,"ImageAlt", "")) %>'></IMG>
		</TD>
		<TD class="ms-alternating ms-featurealtrow" style="padding-top: 4px; padding-bottom: 4px;">
			<TABLE width="100%" cellpadding="0" cellspacing="0" border="0">
				<TR><TD class="ms-vb2" style="font-weight: bold;"><H3 class="ms-standardheader"><%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container.DataItem, "Title", "")) %></H3></TD></TR>
				<TR><TD class="ms-vb2"><%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container.DataItem, "Description", "")) %></TD></TR>
			</TABLE>
		</TD>
		<TD class="ms-alternating ms-featurealtrow" style="padding-top: 4px; padding-bottom: 4px;">
			<DIV id='<%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container.DataItem, "FeatureId", "")) %>'>
				<asp:Button runat="server" UseSubmitBehavior="false" class="ms-ButtonHeightWidth"
							id='btnActivate'
							OnClick="BtnActivateFeature_Click"
							CommandName='<%# DataBinder.Eval(Container.DataItem, "Status") %>'
							CommandArgument='<%# SPHttpUtility.HtmlEncode(DataBinder.Eval(Container.DataItem, "FeatureId", "")) %>'
							Text='<%# DataBinder.Eval(Container.DataItem, "ButtonText") %>' />&nbsp;&nbsp;&nbsp;&nbsp;
			</DIV>
		</TD>
		<TD class="ms-alternating ms-featurealtrow" style="padding-top: 4px; padding-bottom: 4px;">
			<DIV class="ms-vb2 ms-featurestatus" FeatureStatus='<%# DataBinder.Eval(Container.DataItem, "Status") %>'>
					 <span class="ms-featurestatustext"><%# DataBinder.Eval(Container.DataItem, "StatusUI") %></span>&nbsp;
			</DIV>
		</TD>
	</AlternatingItemTemplate>
	<SeparatorTemplate>
		</TR>
		<TR>
	</SeparatorTemplate>
	<FooterTemplate>
		</TR>
       </TABLE>
	</FooterTemplate>
</asp:Repeater>
			<TR><TD colspan=6 class=ms-vb><asp:Label id="lblEmptyFeaturesText" runat=server /></TD></TR>
		</TD>
	</TR>
</TABLE>
<h3><asp:Label ID="lbJobSection" runat="server" /></h3>
<div style="padding-bottom:3px">
<a href="?"><img src="/_layouts/images/refresh.gif" alt='<asp:Literal runat="server" Text="<%$Resources:wss,mobile_button_refresh_text%>" />' style="border:0" /></a> <a href="?"><asp:Literal ID="Literal1" runat="server" Text="<%$Resources:wss,mobile_button_refresh_text%>" /></a> 
</div>
<SharePoint:MenuTemplate ID="mtJobsMenu" runat="server">
    <SharePoint:MenuItemTemplate ID="mitJobDetails" runat="server" Text="Details" ImageUrl="/_layouts/images/detail.gif" ClientOnClickNavigateUrl="/_admin/JobEdit.aspx?JobId=%ID%" Title="Details"></SharePoint:MenuItemTemplate>
    <SharePoint:MenuItemTemplate ID="mitJobLaunch" runat="server" Text="Launch" ImageUrl="/_layouts/images/ServiceNotInstalled.gif" ClientOnClickNavigateUrl="?JobId=%ID%&Launch=true" Title="Launch"></SharePoint:MenuItemTemplate>
</SharePoint:MenuTemplate>
<SharePoint:SPGridView id="gvReportingJobs" runat="server" AutoGenerateColumns="false">
    <Columns>
        <SharePoint:SPMenuField 
            HeaderText="Title" 
            TextFields="Title" 
            MenuTemplateId="mtJobsMenu"
            NavigateUrlFields="Id" 
            NavigateUrlFormat="/_admin/JobEdit.aspx?JobId={0}" 
            TokenNameAndValueFields="ID=Id" />
        <SharePoint:SPBoundField DataField="LastRunTime" HeaderText="LastRunTime" /> 
        <SharePoint:SPBoundField DataField="Schedule" HeaderText="Schedule" /> 
        <SharePoint:SPBoundField DataField="Status" HeaderText="Status" /> 
        <SharePoint:SPBoundField DataField="Progress" HeaderText="Progress" /> 
    </Columns>
</SharePoint:SPGridView>
</asp:Panel>
</asp:Content>
<script runat="server">
    protected override void OnLoad(EventArgs e)
    {
        hlSite.Text = SPContext.Current.Web.Title;
        hlSite.NavigateUrl = SPContext.Current.Web.Url;
        hlSiteSettings.NavigateUrl = SPUrlUtility.CombineUrl(SPContext.Current.Web.Url, "/_admin/applications.aspx");

        if (!Page.IsPostBack)
        {
            LocalizeControls();
            BindFeatures();
            BindJobData();
        }
        
        base.OnLoad(e);
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        
        if (!string.IsNullOrEmpty(Utilities.ReportsCenterUrl))
        {
            ShowOrHideControls(true);
            hlReportsCenter.NavigateUrl = SPUrlUtility.CombineUrl(Utilities.ReportsCenterUrl, Utilities.GetResourceString("SoVSPReportingWeb_ReportsCenterPageUrl"));

            if (Request.QueryString["JobId"] != null)
            {
                Guid jobId = new Guid(Request.QueryString["JobId"]);
                string qsLaunch = Request.QueryString["Launch"];
                string qsLaunched = Request.QueryString["Launched"];
                if (qsLaunch != null) qsLaunch = qsLaunch.ToLowerInvariant();
                if (qsLaunched != null) qsLaunched = qsLaunched.ToLowerInvariant();

                if (qsLaunch == "true")
                {
                    bool launched = JobUtilities.RunJob(jobId);
                    Response.Redirect(SPUrlUtility.CombineUrl(SPContext.Current.Web.Url, string.Format("/_admin/sov/ReportsCenter.aspx?JobId={0}&Launched={1}", jobId, launched)), true);
                }
                else if (qsLaunched == "true")
                {
                    string jsMessage = "Job launched !";
                    jsMessage = jsMessage.Replace("'", "\'");
                    ClientScript.RegisterClientScriptBlock(GetType(), "JobLaunched", string.Format("<scr" + "ipt language=\"javascript\" type=\"text/javascript\">alert('{0}');</sc" + "ript>", jsMessage));
                }
            }

            string featureId = Request.QueryString["featureid"];
            string action = Request.QueryString["action"];
            switch (action)
            {
                case "activate":
                    try
                    {
                        using (SPSite site = new SPSite(Utilities.ReportsCenterUrl))
                        {
                            using (SPWeb web = site.OpenWeb())
                            {
                                if (Utilities.IsReportsCenter(web))
                                {
                                    web.AllowUnsafeUpdates = true;
                                    web.Features.Add(new Guid(featureId), true);
                                    web.AllowUnsafeUpdates = false;
                                    lbReportActivationInfo.Text = Utilities.GetResourceString("SoVSPReporting_ReportingAdmin_FeatureActivated");
                                    lbReportActivationInfo.ForeColor = System.Drawing.Color.ForestGreen;
                                }
                            }
                        }
                    }
                    catch (SPException spex)
                    {
                        lbReportActivationInfo.Text = spex.Message;
                        lbReportActivationInfo.ForeColor = System.Drawing.Color.Red;
                    }
                    break;
                case "deactivate":
                    try
                    {
                        using (SPSite site = new SPSite(Utilities.ReportsCenterUrl))
                        {
                            using (SPWeb web = site.OpenWeb())
                            {
                                if (Utilities.IsReportsCenter(web))
                                {
                                    web.AllowUnsafeUpdates = true;
                                    web.Features.Remove(new Guid(featureId));
                                    web.AllowUnsafeUpdates = false;
                                    lbReportActivationInfo.Text = Utilities.GetResourceString("SoVSPReporting_ReportingAdmin_FeatureDeactivated");
                                    lbReportActivationInfo.ForeColor = System.Drawing.Color.ForestGreen;
                                }
                            }
                        }
                    }
                    catch (SPException spex)
                    {
                        lbReportActivationInfo.Text = spex.Message;
                        lbReportActivationInfo.ForeColor = System.Drawing.Color.Red;
                    }
                    break;
            }
        }
        else
        {
            ShowOrHideControls(false);
        }
        
        btActivateReportsCenter.Click += btActivateReportsCenter_Click;
        btDeactivateReportsCenter.Click += btDeactivateReportsCenter_Click;
    }

    void btDeactivateReportsCenter_Click(object sender, EventArgs e)
    {
        try
        {
            if (Utilities.DeactivateSPReportingFeatures())
            {
                lbReportActivationInfo.Text = Utilities.GetResourceString("SoVSPReporting_ReportingAdmin_FeatureDeactivated");
                lbReportActivationInfo.ForeColor = System.Drawing.Color.ForestGreen;
                ShowOrHideControls(false);
            }
        }
        catch(SPException spex)
        {
            lbReportActivationInfo.Text = spex.Message;
            lbReportActivationInfo.ForeColor = System.Drawing.Color.Red;
        }
    }

    void btActivateReportsCenter_Click(object sender, EventArgs e)
    {
        try
        {
            using(SPSite site = new SPSite(txtbxReportsCenterUrl.Text))
            {
                using(SPWeb web = site.OpenWeb())
                {
                    if (!Utilities.IsReportsCenter(web))
                    {
                        if (Utilities.ActivateReportsCenter(web))
                        {
                            Utilities.ReportsCenterUrl = web.Url;
                            lbReportActivationInfo.Text = Utilities.GetResourceString("SoVSPReporting_ReportingAdmin_FeatureActivated");
                            lbReportActivationInfo.ForeColor = System.Drawing.Color.ForestGreen;
                            ShowOrHideControls(true);
                        }
                    }
                }
            }
        }
        catch(SPException spex)
        {
            lbReportActivationInfo.Text = spex.Message;
            lbReportActivationInfo.ForeColor = System.Drawing.Color.Red;
        }
    }

    void ShowOrHideControls(bool isReportsCenterEnabled)
    {
        pnReportsCenterActivated.Visible = isReportsCenterEnabled;
        btActivateReportsCenter.Visible = !isReportsCenterEnabled;
        btDeactivateReportsCenter.Visible = isReportsCenterEnabled;
        txtbxReportsCenterUrl.Visible = !isReportsCenterEnabled;
        hlReportsCenter.Visible = isReportsCenterEnabled;
    }

    void LocalizeControls()
    {
        string pageTitle = string.Format("{0} - {1}", Utilities.GetResourceString("SoVSPReporting_SoVGroup"), Utilities.GetResourceString("SoVSPReporting_ReportingAdmin_Title"));
        litPageTitle.Text = litPageTitle2.Text = pageTitle;
        lbCurrentPage.Text = Utilities.GetResourceString("SoVSPReporting_ReportingAdmin_Title");
        mitJobDetails.Text = mitJobDetails.Title = Utilities.GetResourceString("SoVSPReporting_ReportingAdmin_Details");
        mitJobLaunch.Text = mitJobLaunch.Title = Utilities.GetResourceString("SoVSPReporting_ReportingAdmin_RunJob");
        foreach (DataControlField field in gvReportingJobs.Columns)
        {
            field.HeaderText = Utilities.GetResourceString(string.Format("SoVSPReporting_ReportingAdmin_Header_{0}", field.HeaderText));
        }
        elitReportsCenterUrlDescription.Text = Utilities.GetResourceString("SoVSPReporting_ReportingAdmin_ReportsCenterUrl_Description");
        elitReportsCenterUrlTitle.Text = Utilities.GetResourceString("SoVSPReporting_ReportingAdmin_ReportsCenterSettings_Title");
        hlReportsCenter.Text = Utilities.GetResourceString("SoVSPReportingWeb_GoToReportsCenter");
    }
    
    void BindFeatures()
    {
        rptrFeatureList.DataSource = Utilities.GetReportsCenterFeatures(SPContext.Current.Web.Language);
        rptrFeatureList.DataBind();
    }
    
    void BtnActivateFeature_Click(object o, EventArgs e)
    {
        Button button = o as Button;
        if (button != null)
        {
            string featureId = button.CommandArgument;
            if (button.CommandName == "")
            {
                // Activate feature
                try
                {
                    using (SPSite site = new SPSite(Utilities.ReportsCenterUrl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            if (Utilities.IsReportsCenter(web))
                            {
                                web.Features.Add(new Guid(featureId), true);
                                lbReportActivationInfo.Text = Utilities.GetResourceString("SoVSPReporting_ReportingAdmin_FeatureActivated");
                                lbReportActivationInfo.ForeColor = System.Drawing.Color.ForestGreen;
                            }
                        }
                    }
                }
                catch (SPException spex)
                {
                    lbReportActivationInfo.Text = spex.Message;
                    lbReportActivationInfo.ForeColor = System.Drawing.Color.Red;
                }
            }
            else 
            {
                // Deactivate feature
                try
                {
                    using (SPSite site = new SPSite(Utilities.ReportsCenterUrl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            if (Utilities.IsReportsCenter(web))
                            {
                                web.Features.Remove(new Guid(featureId));
                                lbReportActivationInfo.Text = Utilities.GetResourceString("SoVSPReporting_ReportingAdmin_FeatureDeactivated");
                                lbReportActivationInfo.ForeColor = System.Drawing.Color.ForestGreen;
                            }
                        }
                    }
                }
                catch (SPException spex)
                {
                    lbReportActivationInfo.Text = spex.Message;
                    lbReportActivationInfo.ForeColor = System.Drawing.Color.Red;
                }
            }

            BindFeatures();
        }
    }

    void BindJobData()
    {
        SPService service = SPFarm.Local.Services.GetValue<SPTimerService>(Globals.SPTimerServiceName);

        DataTable dtJobs = new DataTable("Jobs");
        dtJobs.Columns.Add("Id", typeof(Guid));
        dtJobs.Columns.Add("Title");
        dtJobs.Columns.Add("LastRunTime", typeof(DateTime));
        dtJobs.Columns.Add("Schedule");
        dtJobs.Columns.Add("Status");
        dtJobs.Columns.Add("Progress");

        foreach (SPJobDefinition job in service.JobDefinitions)
        {
            if (job.GetType().IsSubclassOf(typeof(GenericReportingJobDefinition)))
            {
                DataRow dRow = dtJobs.NewRow();
                dRow["Id"] = job.Id;
                dRow["Title"] = job.Title;
                dRow["Schedule"] = job.Schedule.ToString();
                dRow["LastRunTime"] = DateTime.MinValue;
                dRow["Status"] = "-";
                dRow["Progress"] = "0%";

                try
                {
                    SPRunningJob runningJob = service.RunningJobs.GetInstance(job.Id, SPServer.Local.Name);
                    if (runningJob != null)
                    {
                        dRow["Status"] = runningJob.Status.ToString();
                        dRow["Progress"] = string.Format("{0}%", runningJob.PercentageDone);
                        dRow["LastRunTime"] = job.LastRunTime;
                    }
                }
                catch
                {
                    // No running job
                }

                dtJobs.Rows.Add(dRow);
            }
        }

        gvReportingJobs.DataSource = dtJobs;
        gvReportingJobs.DataBind();
    }
</script>